package controller;

import conventer.ResultInfo;
import dao.GoodDAO;
import dao.UserDAO;
import entity.GoodEntity;
import entity.UserEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import utilities.FileUtil;
import utilities.LoginTestUtil;
import utilities.MailUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Timestamp;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Controller
@RequestMapping("/index")
public class GoodController {
    @RequestMapping(value = "/good/publish" , method = POST)
    @ResponseBody
    public Object publishGood(@RequestParam String title,
                              @RequestParam String tag,
                              @RequestParam String price,
                              @RequestParam String detail,
                              @RequestParam(value = "picture", required = true) CommonsMultipartFile picture,
                              HttpServletRequest request,
                              HttpSession session) throws IOException{

        /*String title = "123";
        String tag = "234";
        String price = "123";
        String detail = "dtl";*/

        ResultInfo result = new ResultInfo();
        if(!LoginTestUtil.isLoggedin(session)) {
            result.setResult("ERROR");
            result.setReason("YOU ARE NOT LOGGED IN");
            return result;
        }
        //如果用“.”作为分隔的话，必须是如下写法：String.split("\\."),这样才能正确的分隔开，不能用String.split(".");
        //如果用“|”作为分隔的话，必须是如下写法：String.split("\\|"),这样才能正确的分隔开，不能用String.split("|"); “.”和“|”都是转义字符，必须得加"\\";
        System.out.println(picture.getOriginalFilename().split("\\.")[0]);
        String filepath = "G:\\Files\\RJGC\\SecondHandMarket\\out\\artifacts\\SecondHandMarket_war_exploded\\resource\\picture\\shangpinxiangqing";
        String filename = session.getAttribute("userid").toString()+System.currentTimeMillis()+picture.getOriginalFilename().split("\\.")[1];
        String virtualPath = "pic/shangpinxiangqing";

        byte[] bytePic = picture.getBytes();
        FileUtil.byteToFile(bytePic,filepath ,filename);
        if(GoodDAO.publish(Integer.parseInt(session.getAttribute("userid").toString()),title,detail,price,tag,virtualPath+"/"+filename)){
            result.setResult("SUCCESS");
        }else{
            result.setResult("FAILED");
            result.setReason("PUBLISH_FAILED");
        }

        return result;
    }

    @RequestMapping(value = "/good", method = GET)
    @ResponseBody
    public Object getGoodList(@RequestParam String fromTime,
                              @RequestParam(value = "tag", required = false) String tag,
                              @RequestParam int startat,
                              @RequestParam int endat,
                              HttpSession sesson,
                              HttpServletResponse response)
    {
        ResultInfo result = new ResultInfo();
        if(!LoginTestUtil.isLoggedin(sesson)) {
            result.setResult("ERROR");
            result.setReason("YOU ARE NOT LOGGED IN");
            return result;
        }


        GoodEntity[] resultArray = GoodDAO.getGoods(tag,new Timestamp(Long.parseLong(fromTime)),startat,endat);
        if(resultArray == null || resultArray.length == 0){
            result.setResult("FAILED");
            result.setReason("THERE IS NO RESULTS");
        }else{
            result.setResult("SUCCESS");
            result.setData(resultArray);
        }
        return result;
    }

    @RequestMapping(value = "/good/search", method = GET)
    @ResponseBody
    public Object searchGoodList(@RequestParam String fromTime,
                              @RequestParam String keyword,
                              @RequestParam int startat,
                              @RequestParam int endat,
                              HttpSession sesson,
                              HttpServletResponse response)
    {
        ResultInfo result = new ResultInfo();
        if(!LoginTestUtil.isLoggedin(sesson)) {
            result.setResult("ERROR");
            result.setReason("YOU ARE NOT LOGGED IN");
            return result;
        }


        GoodEntity[] resultArray = GoodDAO.searchGoods(keyword,new Timestamp(Long.parseLong(fromTime)),startat,endat);
        if(resultArray == null || resultArray.length == 0){
            result.setResult("FAILED");
            result.setReason("THERE IS NO RESULTS");
        }else{
            result.setResult("SUCCESS");
            result.setData(resultArray);
        }
        return result;
    }

    @RequestMapping(value = "/good/info", method = GET)
    @ResponseBody
    public Object getInfo(@RequestParam int id,
                          HttpSession session){
        ResultInfo result = new ResultInfo();
        if(!LoginTestUtil.isLoggedin(session)) {
            result.setResult("ERROR");
            result.setReason("YOU ARE NOT LOGGED IN");
            return result;
        }


        GoodEntity resultObj = GoodDAO.getGoodInfo(id);
        if(resultObj == null){
            result.setResult("FAILED");
            result.setReason("GET GOOD INFO FAILED");
        }else{
            result.setResult("SUCCESS");
            result.setData(resultObj);
        }
        return result;
    }

    @RequestMapping(value = "/good/buy", method = POST)
    @ResponseBody
    public Object buy(@RequestParam int sellerid,
                          @RequestParam int goodid,
                          @RequestParam String goodtitle,
                          HttpSession session) {
        ResultInfo result = new ResultInfo();
        if(!LoginTestUtil.isLoggedin(session)) {
            result.setResult("ERROR");
            result.setReason("YOU ARE NOT LOGGED IN");
            return result;
        }

        try{
            UserEntity seller = UserDAO.getUserByID(sellerid);
            UserEntity buyer = UserDAO.getUserByID(Integer.parseInt(session.getAttribute("userid").toString()));
            GoodDAO.buySellOrDelete(goodid,buyer.getId(),"sold");
            if(MailUtil.sendBuy(buyer.getEmail(),buyer.getUsername(),seller.getEmail(),seller.getUsername(),goodtitle))
                result.setResult("SUCCESS");
            else {
                result.setResult("FAILED");
                result.setReason("BUY EMAIL SEND FAILED");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setResult("ERROR");
        }finally {
            return result;
        }
    }
}
